package org.enhance.mybatis.ddl;

import com.baomidou.mybatisplus.annotation.DbType;
import org.enhance.common.exception.AssertionException;
import org.enhance.mybatis.ddl.model.TableDefine;
import org.enhance.mybatis.util.DdlUtil;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.util.List;
import java.util.Map;

public class GenerateDdlFactory {
    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public GenerateDdlFactory(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }

    public Map<String, List<String>> generate(List<TableDefine> tableDefines, DbType dbType) {
        AbstractDdlGenerate generate;
        switch (dbType) {
            case MYSQL:
            case MARIADB:
                generate = new MysqlDdlGenerate(namedParameterJdbcTemplate.getJdbcTemplate());
                break;
            case SQLITE:
                generate = new SqliteDdlGenerate(namedParameterJdbcTemplate.getJdbcTemplate());
                break;
            default:
                throw new AssertionException(String.format("Unsupport dbType {} generate.", dbType));
        }
        return generate.generate(tableDefines);
    }

    public boolean tableExist(String tableName, DbType dbType) {
        AbstractDdlGenerate generate;
        switch (dbType) {
            case MYSQL:
            case MARIADB:
                generate = new MysqlDdlGenerate(namedParameterJdbcTemplate.getJdbcTemplate());
                break;
            case SQLITE:
                generate = new SqliteDdlGenerate(namedParameterJdbcTemplate.getJdbcTemplate());
                break;
            default:
                throw new AssertionException(String.format("Unsupport dbType {} generate.", dbType));
        }
        String schema = DdlUtil.getDbName();
        return generate.tableExist(schema, tableName);
    }
}